<!--
 /**
 * Author: hongChengHao
 * Date: 2022-07-22 09:25
 * Desc: merchantsCoupon 商品券
 */
-->
<template>
  <view class="merchants-coupon" :class="isShow ? 'no-scroll' : ''">
    <!-- #ifdef MP-WEIXIN || MP-ALIPAY-->
    <yy-navbar :auto-back="false" @left-click="backClick" title="商品券" bg-color="#fff"></yy-navbar>
    <!-- #endif-->
    <view class="merchants-coupon__filter">
      <view class="merchants-coupon__sel">
        <yy-select
          v-model="hasSelect"
          api-name="coupon"
          api-key="getCinemaBusinessList"
          placeholder="请选择商户"
          val-key="id"
          label-key="name"
          has-all
          :disabled="isDisabled"
        ></yy-select>
      </view>
      <view class="ml20 mr10 merchants-coupon__scan" @click.stop="onScan"></view>
    </view>
    <yy-list :list="listData" :loading="listLoading" :finished="listFinished" empty-type="coupon">
      <view class="merchants-coupon__coupon-box">
        <coupon-box v-for="(item, index) in listData" :key="index">
          <view slot="left" class="merchants-coupon__coupon-main">
            <view class="merchants-coupon__coupon-money onShow">{{ item.name || '--' }}</view>
            <view class="onShow">{{ item.startTime || '--' }}~{{ item.endTime || '--' }}</view>
          </view>

          <view slot="right">
            <view v-if="!isScan" class="merchants-coupon__coupon-btn" @click.stop="toUse(item)">立即使用</view>
            <view v-else class="merchants-coupon__select" @click="onSel(item, index)">
              <view class="merchants-coupon__use-bg" :class="val.canUse ? 'merchants-coupon__use' : 'merchants-coupon__no-use'"></view>
              <view v-if="val.canUse" class="merchants-coupon__ck" :class="val.isSel === '1' ? 'merchants-coupon__check' : 'merchants-coupon__no-check'"></view>
            </view>
          </view>
        </coupon-box>
      </view>
    </yy-list>
    <check-film-coupon :type="isScan ? '3' : '1'" title="历史记录" :arr="listData" url="/pagesOrder/invalidCoupon/index"></check-film-coupon>
    <coupon-detail v-if="listData && listData.length > 0" v-model="isShow" :obj="couponInfo" :arr="listData" :qr-url="qrUrl"></coupon-detail>
  </view>
</template>
<script>
  import CouponBox from '@/pagesOrder/components/CouponBox/index.vue'
  import CheckFilmCoupon from '@/pagesOrder/components/CheckFilmCoupon/index.vue'
  import listMixins from '@/mixins/listMixins'
  import CouponDetail from '@/pagesOrder/components/CouponDetail/index.vue'
  // #ifdef H5
  import { scanQRCode } from '@/utils/sdk'
  // #endif
  export default {
    name: 'merchants-coupon',
    components: {
      CouponBox,
      CheckFilmCoupon,
      CouponDetail
    },
    mixins: [listMixins],
    data() {
      return {
        hasSelect: '-1',
        total: 0,
        isShow: false,
        couponInfo: {},
        isScan: false,
        isDisabled: false
      }
    },
    onLoad(options) {
      if (options.businessId) {
        this.hasSelect = options.businessId
        this.isDisabled = true
        this.isScan = true
      }
    },
    // #ifdef MP-ALIPAY
    onUnload() {
      this.$tools.navigateTo('/pages/mine/index', {}, 'switchTab')
    },
    // #endif
    onShow() {
      console.log('接口请求中:', new Date())
      this.listLoad()
      if (this.isScan) {
        this.listRefresh()
      }
    },
    computed: {
      qrUrl() {
        const arr = []
        this.listData.forEach((item) => {
          const qrCode = item.interfacePickUpCode || item.code
          arr.push(this.$utils.qrcodeCreate(qrCode))
        })
        return arr
      }
    },
    watch: {
      hasSelect(data) {
        console.log('watch hasSelect', data)
        this.listRefresh()
      }
    },
    methods: {
      backClick() {
        const fromPath = this.$tools.getCurrentPage().fromPath
        if (fromPath === 'pagesOrder/order/detail') {
          this.$tools.navigateTo(-1)
        } else {
          this.$tools.navigateTo('/pages/mine/index', {}, 'switchTab')
        }
      },
      onloadList() {
        const query = {
          ...this.search,
          ...this.pageInfo,
          version: '2',
          businessId: this.hasSelect
        }
        return uni.$api.coupon.getMerchandiseCouponList(query).then((res) => {
          if (this.isLoading) {
            // 是下啦刷新 清空
            this.listData = []
          }
          this.listData = [...this.listData, ...res.list]
          console.log('this.listData', this.listData)
          return res
        })
      },
      // onPullDownRefresh() {
      //   console.log('外部onPullDownRefresh')
      //   this.listRefresh()
      // },
      onReachBottom() {
        this.listLoad()
      },
      toUse(val) {
        this.isShow = true
        this.couponInfo = val
      },
      onScan() {
        // #ifdef MP-ALIPAY
        uni.scanCode({
          success: (res) => {
            this.bindCode(res.result)
          }
        })
        // #endif
        // #ifdef MP-WEIXIN ||  MP-TOUTIAO
        uni.authorize({
          scope: 'scope.camera',
          success: () => {
            uni.scanCode({
              scanType: 'qrCode',
              success: (res) => {
                this.bindCode(res.result)
              },
              complete: (res) => {
                console.log('complete	', res)
              }
            })
          },
          fail: () => {
            //授权失败
            uni.showModal({
              title: '该功能需摄像头授权',
              content: '是否进入权限管理，调整授权？',
              success: (res) => {
                if (res.confirm) {
                  //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                  uni.openSetting({
                    success: (res) => {
                      console.log(res.authSetting)
                    }
                  })
                } else if (res.cancel) {
                  return uni.showToast({
                    title: '已取消！'
                  })
                }
              }
            })
          }
        })
        // #endif
        // #ifdef H5
        scanQRCode().then((res) => {
          this.bindCode(res)
        })
        // #endif
      },
      bindCode(res) {
        console.log(res, 'success')
        const query = res.split('?')[2].split('&')[1]
        const businessId = query.split('=')[1]

        this.hasSelect = businessId
        this.isDisabled = true
        this.isScan = true
        this.listRefresh()
      },
      onSel(val, index) {
        if (val.canUse) {
          if (val.isSel === '1') {
            this.$set(this.listData[index], 'isSel', '0')
          } else {
            this.$set(this.listData[index], 'isSel', '1')
          }
        } else {
          this.$msg.toast('未到生效时间,暂不能使用')
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .no-scroll {
    overflow-y: hidden;
  }
  .merchants-coupon {
    box-sizing: border-box;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 100%;
    background: #f3f5f7;
    color: #919191;
    padding-bottom: 250rpx;
    min-height: 100vh;

    &__filter {
      border-top: 1px solid #eee;
      padding: 20rpx;
      display: flex;
      align-items: center;
      background: #fff;
    }
    &__sel {
      flex: 1;
    }
    &__scan {
      width: 50rpx;
      height: 50rpx;
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/icon-scan.png) no-repeat;
      background-size: 100%;
    }

    &__name {
      padding: 37rpx 31rpx 27rpx;
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
    }
    &__nopadding {
      padding-top: 17rpx;
    }
    &__coupon-box {
      margin-top: 20rpx;
      width: 100%;
      padding: 0 20rpx;
    }
    &__coupon-main {
      display: flex;
      flex-direction: column;
      padding: 35rpx;
      justify-content: space-between;
      height: 100%;
      box-sizing: border-box;
      font-size: 24rpx;
      color: #919191;
    }
    &__coupon-money {
      font-size: 34rpx;
      font-weight: 600;
      color: #333333;
    }
    &__coupon-btn {
      // margin-top: 50%;
      // margin-left: 48%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 130rpx;
      height: 56rpx;
      background: linear-gradient(135deg, #ffa633 0%, #f8a82d 100%);
      border-radius: 16rpx;
      font-size: 24rpx;
      color: #ffffff;
      line-height: 56rpx;
      text-align: center;
    }
    &__select {
      position: relative;
      overflow: hidden;
    }
    &__use-bg {
      margin-top: 50%;
      margin-left: 48%;
      transform: translate(-50%, -50%);
      width: 96rpx;
      height: 96rpx;
    }
    &__use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-active.png) no-repeat;
      background-size: 100%;
    }
    &__no-use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-noActive.png) no-repeat;
      background-size: 100%;
    }
    &__ck {
      position: absolute;
      top: 0;
      right: 0;
      width: 50rpx;
      height: 50rpx;
    }
    &__check {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/check.png) no-repeat;
      background-size: 100%;
    }
    &__no-check {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/no-check.png) no-repeat;
      background-size: 100%;
    }
  }
</style>
